import 'package:cloud_medicine/components/tag.dart';
import 'package:cloud_medicine/components/user_avatar.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/post_api.dart';
import 'package:cloud_medicine/http/prescription_api.dart';
import 'package:cloud_medicine/http/user_api.dart';
import 'package:cloud_medicine/model/base_user_info.dart';
import 'package:cloud_medicine/model/post_list.dart';
import 'package:cloud_medicine/model/prescription_list.dart';
import 'package:cloud_medicine/pages/post_detail.dart';
import 'package:cloud_medicine/pages/prescription_detail.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class OtherUserShowPage extends StatefulWidget {
  final int userID;

  OtherUserShowPage({
    Key key,
    @required this.userID,
  }) : super(key: key);

  @override
  _OtherUserShowPageState createState() => _OtherUserShowPageState();
}

class _OtherUserShowPageState extends State<OtherUserShowPage> {
  bool _loading = false;
  bool _listLoading = false;
  BaseUserInfo _baseUserInfo;
  int currentIndex = 0; // tab导航
  List<PostItem> _postList = [];
  List<PrescriptionItem> _prescriptionList = [];
  final TextStyle tipTextStyle = TextStyle(
    color: Colors.grey,
    fontSize: 12,
  );
  final Map<int, dynamic> urlConstracts = {
    0: getPostList_api,
    1: getPrescriptionList_api
  };

  @override
  void initState() {
    super.initState();
    _loadData();
    _loadListData();
  }

  // 加载数据
  Future<Null> _loadData() async {
    setState(() {
      _loading = true;
    });
    dynamic res = await getOtherUserInfo_api('$backIP/user/basic', {
      'userID': widget.userID,
    });
    if (mounted) {
      setState(() {
        _loading = false;
        if (res['code'] == 0) {
          _baseUserInfo = BaseUserInfo.init(res['data']);
        } else {
          errorToast(res['message']);
        }
      });
    }
  }

  // 加载数据
  Future<Null> _loadListData() async {
    _postList.clear();
    _prescriptionList.clear();
    setState(() {
      _listLoading = true;
    });
    String url =
        currentIndex == 0 ? '$backIP/post/list' : '$backIP/prescription/list';
    dynamic res = await urlConstracts[currentIndex](url, {
      'userID': widget.userID,
    });
    res['data'].forEach((dynamic item) {
      if(currentIndex == 0) {
        if(mounted) {
          setState(() {
            PostItem postItemModel = PostItem.init(item);
            _postList.add(postItemModel);
          });
        }
      }else{
        if(mounted) {
          setState(() {
            PrescriptionItem prescriptionItemModel = PrescriptionItem.init(item);
            _prescriptionList.add(prescriptionItemModel);
          });
        }
      }
    });
    setState(() {
      _listLoading = false;
    });
  }

  _buildInfo(String num, String type) {
    final Map<String, String> constractTypes = {'post': '帖子数', 'like': '点赞数'};
    return Column(
      children: <Widget>[
        Text(
          num,
          style: TextStyle(color: Colors.grey, fontSize: 18),
        ),
        SizedBox(height: 5),
        Text(constractTypes[type]),
      ],
    );
  }

  _buildTab(String title, int index) {
    return InkWell(
      onTap: () {
        setState(() {
          currentIndex = index;
        });
        _loadListData();
      },
      child: Container(
        width: 100,
        height: 40,
        decoration: BoxDecoration(
          border: currentIndex == index
              ? Border(
                  bottom: BorderSide(
                  color: Colors.blue,
                  width: 2,
                ))
              : Border(),
        ),
        alignment: Alignment.center,
        child: Text(
          title,
          style: TextStyle(
            color: currentIndex == index ? Colors.blue : Colors.black,
          ),
        ),
      ),
    );
  }

  _entryPage(int id) {
    if (currentIndex == 0) {
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => PostDetail(
          postID: id,
        ),
      ));
    } else {
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => PrescriptionDetailPage(
          id: id,
        ),
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('用户信息显示'),
      ),
      body: _loading
          ? loadingWidget(_loading)
          : ListView(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.fromLTRB(10, 20, 10, 20),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          UserAvatar(
                            avatar: _baseUserInfo.avatar,
                          ),
                          SizedBox(width: 10),
                          Container(
                            height: 80,
                            child: Column(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(_baseUserInfo.realname,
                                    style: TextStyle(fontSize: 24)),
                                Row(
                                  children: <Widget>[
                                    Tag(
                                      text: _baseUserInfo.identify.value,
                                      bgColor: Colors.green,
                                    ),
                                    SizedBox(width: 10),
                                    _baseUserInfo.statusID != 0
                                        ? Tag(
                                            text: getDoctorStatusInfo(
                                              _baseUserInfo.statusID,
                                              'text',
                                            ),
                                            bgColor: getDoctorStatusInfo(
                                              _baseUserInfo.statusID,
                                              'bgColor',
                                            ),
                                          )
                                        : Container(),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: <Widget>[
                          _buildInfo(_baseUserInfo.postNum, 'post'),
                          SizedBox(width: 20),
                          _buildInfo(_baseUserInfo.likeNum, 'like'),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  height: 20,
                  color: Colors.grey[200],
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: Row(
                    children: <Widget>[
                      _buildTab('帖子', 0),
                      _buildTab('处方', 1),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(bottom: 10),
                  height: 1,
                  color: Colors.grey[200],
                ),
                _listLoading
                    ? loadingWidget(_listLoading)
                    : ListView.builder(
                        itemCount: currentIndex == 0
                            ? _postList.length
                            : _prescriptionList.length,
                        shrinkWrap: true,
                        physics: new NeverScrollableScrollPhysics(),
                        itemBuilder: (BuildContext context, int index) {
                          return ListView(
                            shrinkWrap: true,
                            physics: new NeverScrollableScrollPhysics(),
                            children: <Widget>[
                              InkWell(
                                onTap: () {
                                  _entryPage(currentIndex == 0
                                      ? _postList[index].id
                                      : _prescriptionList[index].id);
                                },
                                child: Container(
                                  padding: EdgeInsets.all(10),
                                  child: ListView(
                                    shrinkWrap: true,
                                    physics: new NeverScrollableScrollPhysics(),
                                    children: <Widget>[
                                      Text(
                                        currentIndex == 0
                                            ? _postList[index].abstract
                                            : _prescriptionList[index].abstract,
                                        maxLines: 3,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      SizedBox(height: 15),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: <Widget>[
                                          currentIndex == 0
                                              ? Row(
                                                  children: <Widget>[
                                                    Text(
                                                      '${_postList[index].like_num}点赞',
                                                      style: tipTextStyle,
                                                    ),
                                                    SizedBox(width: 5),
                                                    Text(
                                                      '${_postList[index].comment_num}评论',
                                                      style: tipTextStyle,
                                                    ),
                                                  ],
                                                )
                                              : Container(),
                                          Text(
                                            currentIndex == 0
                                                ? _postList[index].createTime
                                                : _prescriptionList[index]
                                                    .createTime,
                                            style: tipTextStyle,
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              Container(
                                height: 1,
                                color: Colors.grey[200],
                              ),
                            ],
                          );
                        },
                      )
              ],
            ),
    );
  }
}
